package com.anrongtec.zcpt.fragment;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.adapter.common.CommonAdapter;
import com.anrongtec.zcpt.adapter.common.MultiItemTypeAdapter;
import com.anrongtec.zcpt.adapter.common.ViewHolder;
import com.anrongtec.zcpt.base.BaseFragment;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.constant.JsonDataRestult;
import com.anrongtec.zcpt.constant.URLConstants;
import com.anrongtec.zcpt.listener.AppBarStateChangeListener;
import com.anrongtec.zcpt.model.AppManagerModel;
import com.anrongtec.zcpt.model.AppModel;
import com.anrongtec.zcpt.model.BannerApp;
import com.anrongtec.zcpt.model.PageList;
import com.anrongtec.zcpt.ui.activity.AppDetailActivity;
import com.anrongtec.zcpt.ui.activity.DownloadManagerActivity;
import com.anrongtec.zcpt.utils.ApkUtils;
import com.anrongtec.zcpt.utils.FileUtils;
import com.anrongtec.zcpt.utils.GsonUtil;
import com.anrongtec.zcpt.utils.HttpUtil;
import com.anrongtec.zcpt.utils.SpacesItemDecoration;
import com.anrongtec.zcpt.utils.ToastShow;
import com.anrongtec.zcpt.utils.Util;
import com.anrongtec.zcpt.widget.VerticalSwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.lzy.okhttputils.callback.StringCallback;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerClickListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
@SuppressLint("ValidFragment")
public class StoreFragment extends BaseFragment {
    private ViewPager viewPager;
    private RecyclerView rv_latest, rv_download, rv_comment;
    private TabLayout tabLayout;
    private Banner banner;
    private AppBarLayout appbarLayout;

    private String[] tabName;
    private CommonAdapter<AppModel> adapter;
    /**
     * 全部应用, 更新, 应用管理
     */
    private List<AppModel> latest, download, comment;

    private Intent intent;

    /**
     * 当前查询页
     */
    private int page = 1;
    private PagerAdapter pagerAdapter;
    /**
     * banner
     */
    private ArrayList<String> imageUrls;
    private VerticalSwipeRefreshLayout swipe_refresh;
    /**
     * 加载页面
     */
    private View loading;
    /**
     * 消失动画
     */
    private Animation out;

    private List<AppManagerModel> appManagerModelList;

    private final static int APPVIEWTYPE = 1;
    private final static int UPDATEVIEWTYPE = 2;
    private final static int MANAGERVIEWTYPE = 3;


    private static final String CACHE_BANNER = "banner";

    private OnBannerClickListener bannerListener;

    private String myTabName;
    private int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

    private Timer timer;
    private TimerTask task;

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:

                    break;
                case 999:
                    Button btn_load = (Button) msg.obj;
                    repeatTime(btn_load);
                case 1000:
                    loading.setAnimation(out);
                    loading.setVisibility(View.GONE);
                    stopRefresh();
                    break;
            }
        }
    };
    private int mCount;

    public StoreFragment() {
    }

    public StoreFragment(String fName) {
        this.myTabName = fName;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_store, null);
        // View v = inflater.inflate(R.layout.default_loading, null);
        handler.sendEmptyMessageDelayed(1000, 1000);
        initViews(v);

        return v;
    }

    protected void initViews(View view) {
        requestStoragePermission();
        initLoading(view);
        initSwipeRefresh(view);
        initAppBarLayout(view);
        initData();
        initRecyclerView(view);
        initViewPager(view);
        initTabLayout(view);
//        initBanner(view);
    }

    /**
     * 刷新ui  下载进度
     */
    private void repeatTime(final Button button) {
        task = new TimerTask() {
            @Override
            public void run() {
                mCount += 2;
                if (mCount == 100){
                    task.cancel();
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        button.setText(mCount + "%");

                    }
                });
            }
        };

        timer = new Timer();
        // 参数：
        // 1000，延时1秒后执行。
        // 2000，每隔2秒执行1次task。
        timer.schedule(task, 1, 200);
    }

    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
        }
    }

    /**
     * 初始化加载页面
     *
     * @param view
     */
    private void initLoading(View view) {
        loading = view.findViewById(R.id.loading);
        out = AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out);
    }

    /**
     * 初始化appbarlayout
     */
    private void initAppBarLayout(View view) {
        appbarLayout = (AppBarLayout) view.findViewById(R.id.appbarlayout_tab02);
        appbarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    // TODO 禁用下拉刷新 展开状态
                    swipe_refresh.setEnabled(true);
                } else if (state == State.COLLAPSED) {
                    // 折叠状态
                    swipe_refresh.setEnabled(false);
                } else {
                    // 中间状态
                }
            }
        });
    }

    /**
     * 初始化下拉刷新
     *
     * @param view
     */
    private void initSwipeRefresh(View view) {
        swipe_refresh = (VerticalSwipeRefreshLayout) view.findViewById(R.id.swipe_tab02_refresh);
        swipe_refresh.setColorSchemeResources(android.R.color.holo_blue_bright);
        swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getApps(URLConstants.SORT_LATEST, page);
                getApps(URLConstants.SORT_DOWNLOAD, page);
                getApps(URLConstants.SORT_COMMENT, page);
//                getBanners();
            }
        });
    }

    /**
     * 设置BannerView数据源
     */
//    private void initBanner(View view) {
//        banner = (Banner) view.findViewById(R.id.bv_tab02_banner);
//        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
//        banner.setIndicatorGravity(BannerConfig.RIGHT);
//
//        // 拿缓存地址先显示
//        ArrayList<String> images = (ArrayList<String>) AppCacheUtils.getInstance(getActivity(), CACHE_BANNER)
//                .getObject(CACHE_BANNER);
//        banner.setImages(images);
//
//        imageUrls = new ArrayList<String>();
//        // 再获取最新banner信息显示
//        getBanners();
//    }
    protected void initData() {
        tabName = new String[]{"全部应用", "更新", "管理"};
        latest = new ArrayList<>();
        download = new ArrayList<>();
        comment = new ArrayList<>();
        appManagerModelList = new ArrayList<>();


        AppManagerModel appManagerModelA = new AppManagerModel();
        AppManagerModel appManagerModelB = new AppManagerModel();
        AppManagerModel appManagerModelC = new AppManagerModel();
        appManagerModelA.setAppManagerTitle("下载管理");
        appManagerModelB.setAppManagerTitle("已安装管理");
        appManagerModelC.setAppManagerTitle("安装包管理");
        appManagerModelA.setAppManagerContent("查看、删除下载记录");
        appManagerModelB.setAppManagerContent("快速卸载应用");
        appManagerModelC.setAppManagerContent("可删除安装包");
        appManagerModelList.add(appManagerModelA);
        appManagerModelList.add(appManagerModelB);
        appManagerModelList.add(appManagerModelC);

        // 获取app信息
        getApps(URLConstants.SORT_LATEST, page);
        getApps(URLConstants.SORT_DOWNLOAD, page);
        getApps(URLConstants.SORT_COMMENT, page);
    }

    /**
     * 联网获取banner信息
     */
//    private void getBanners() {
//        String json = GsonUtil.toBannerJson();
//        HttpUtil.post(json, new StringCallback() {
//            @Override
//            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
//                JsonDataRestult<PageList<FileId>> result = GsonUtil.decode(arg1,
//                        new TypeToken<JsonDataRestult<PageList<FileId>>>() {
//                        }.getType());
//                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
//                    final ArrayList<FileId> carousels = result.getData().getCarousels();
//                    if (Util.isEmpty(carousels)) {
//                        LogUtil.trace(Log.DEBUG, "TAB02", "banner is empty");
//                        return;
//                    }
//                    imageUrls.clear();
//                    for (int i = 0; i < carousels.size(); i++) {
//                        imageUrls.add(carousels.get(i).getFileId());
//                    }
//                    // imageUrls.add("http://static.zuiyouxi.com/web/attached/image/20160216/20160216115111_54890.jpg");
//                    // imageUrls.add("http://static.zuiyouxi.com/web/attached/image/20160216/20160216115104_22429.jpg");
//                    banner.setImages(imageUrls);
//                    banner.setOnBannerClickListener(new OnBannerClickListener() {
//                        @Override
//                        public void OnBannerClick(int position) {
//                            position = position - 1;
//                            ToBannerApp(carousels.get(position).getPkg(), carousels.get(position).getVersionCode());
//                        }
//                    });
//
//                    // banner.setImageResoucesUrl(imageUrls, new
//                    // OnBannerImageClickListener() {
//                    // @Override
//                    // public void onImageClick(int position, String url) {
//                    //
//                    // String pkg = carousels.get(position).getPkg();
//                    // int versionCode =
//                    // carousels.get(position).getVersionCode();
//                    //
//                    // ToBannerApp(pkg, versionCode);
//                    // }
//                    // });
//
//                    // ArrayList<String> images = (ArrayList<String>)
//                    // AppCacheUtils.getInstance(getActivity(),
//                    // CACHE_BANNER).getObject(CACHE_BANNER);
//                    // bv_tab02_banner.setImageResoucesUrl(images,null);
//
//                    // 缓存banner地址
//                    AppCacheUtils.getInstance(getActivity(), CACHE_BANNER).put(CACHE_BANNER, imageUrls);
//
//                } else {
//                    ToastShow.shortMessage(result.getRetMsg());
//                    if (result.getRetMsg() != null){
//                        Toast.makeText(getActivity(), result.getRetMsg(), Toast.LENGTH_SHORT).show();
//                    }else {
//                        Toast.makeText(getActivity(), "无返回值", Toast.LENGTH_SHORT).show();
//                    }
//                }
//            }
//
//        });
//}

    /**
     * 跳转到详情页面并显示轮播图的app
     *
     * @param versionCode
     * @param pkg
     */
    private void ToBannerApp(String pkg, int versionCode) {
        if (TextUtils.isEmpty(pkg)) {
            ToastShow.shortMessage("广告页");
            return;
        }
        String json = GsonUtil.toSearchApp(pkg, versionCode);
        HttpUtil.post(json, new StringCallback() {
            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
                JsonDataRestult<BannerApp> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<BannerApp>>() {
                }.getType());

                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    if (result.getData().getApp() != null) {
                        intent = new Intent(getActivity(), AppDetailActivity.class);
                        intent.putExtra(Constant.DATA, result.getData().getApp());
                        startActivity(intent);
                    } else {
                        ToastShow.shortMessage("暂无信息");
                    }
                } else {
                    ToastShow.shortMessage("广告页");
                }
            }

            @Override
            public void onError(boolean isFromCache, Call call, Response response, Exception e) {
                if (response == null) {
                    ToastShow.shortMessage(getString(R.string.alert_failed_connect));
                }
                super.onError(isFromCache, call, response, e);
            }
        });
    }

    /**
     * 联网获取apps信息
     */
    private void getApps(final int sort, int page) {

        String json = GsonUtil.toQueryJson("", sort, null, null, page);
        HttpUtil.post(json, new StringCallback() {
            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
                JsonDataRestult<PageList<AppModel>> result = GsonUtil.decode(arg1,
                        new TypeToken<JsonDataRestult<PageList<AppModel>>>() {
                        }.getType());
                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    switch (sort) {
                        case URLConstants.SORT_COMMENT:
                            comment.clear();
                            comment.addAll(result.getData().getApps());
                            rv_comment.getAdapter().notifyDataSetChanged();
                            break;
                        case URLConstants.SORT_DOWNLOAD:
                            download.clear();
                            download.addAll(result.getData().getApps());
                            rv_download.getAdapter().notifyDataSetChanged();
                            break;
                        case URLConstants.SORT_LATEST:
                            latest.clear();
                            latest.addAll(result.getData().getApps());
                            rv_latest.getAdapter().notifyDataSetChanged();
                            break;
                    }
                    pagerAdapter.notifyDataSetChanged();

                } else {
                    if (result.getRetMsg() != null) {
                        Toast.makeText(getActivity(), result.getRetMsg(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getActivity(), "无返回值", Toast.LENGTH_SHORT).show();
                    }
//                    Toast.makeText(getActivity(), result.getRetMsg(), Toast.LENGTH_LONG).show();
//                    ToastShow.shortMessage(result.getRetMsg());
                }
                // TODO loading控件消失
                loading.setAnimation(out);
                loading.setVisibility(View.GONE);
                stopRefresh();
            }

            @Override
            public void onError(boolean isFromCache, Call call, Response response, Exception e) {
                loading.setAnimation(out);
                loading.setVisibility(View.GONE);
                super.onError(isFromCache, call, response, e);

                stopRefresh();

            }

        });
    }

    /**
     * 停止
     */
    private void stopRefresh() {
        if (swipe_refresh == null) {
            return;
        }
        if (swipe_refresh.isRefreshing()) {
            swipe_refresh.setRefreshing(false);
        }
    }

    /**
     * 更新
     */
    public void refresh() {
        if (rv_latest.getAdapter() != null) {
            rv_latest.getAdapter().notifyDataSetChanged();
        }
        if (rv_download.getAdapter() != null) {
            rv_download.getAdapter().notifyDataSetChanged();
        }
        if (rv_comment.getAdapter() != null) {
            rv_comment.getAdapter().notifyDataSetChanged();
        }
        if (pagerAdapter != null) {
            pagerAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化tablayout
     */
    private void initTabLayout(View view) {
        tabLayout = (TabLayout) view.findViewById(R.id.tab02_tablayout);
        tabLayout.setupWithViewPager(viewPager);
    }

    /**
     * 初始化recyclerview
     *
     * @param view
     */
    private void initRecyclerView(View view) {
        rv_latest = new RecyclerView(getContext());
        rv_download = new RecyclerView(getContext());
        rv_comment = new RecyclerView(getContext());

        SpacesItemDecoration decoration = new SpacesItemDecoration(8);
        rv_comment.addItemDecoration(decoration);

        List<AppModel> appsFromSystem = ApkUtils.getAppsFromSystem(getActivity());
        latest.addAll(appsFromSystem);
        setRecyclerAdapter(rv_latest, latest, APPVIEWTYPE);
        setRecyclerAdapter(rv_download, download, UPDATEVIEWTYPE);
        setRecyclerAdapter(rv_comment, comment, MANAGERVIEWTYPE);
    }

    /**
     * 初始化recycler
     */
    private void initViewPager(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.tab02_viewpager);

        pagerAdapter = new PagerAdapter() {
            @Override
            public Object instantiateItem(ViewGroup container, int position) {

                switch (position) {
                    case 0:
                        container.addView(rv_latest);
                        return rv_latest;
                    case 1:
                        container.addView(rv_download);
                        return rv_download;
                    case 2:
                        container.addView(rv_comment);
                        return rv_comment;

                    default:
                        break;
                }

                RecyclerView recyclerView = new RecyclerView(getContext());
                return recyclerView;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return tabName[position];
            }

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                // super.destroyItem(container, position, object);
                // TODO viewpager页面销毁
                ((ViewPager) container).removeView((View) object);
            }

            @Override
            public int getCount() {
                return tabName.length;
            }

            @Override
            public int getItemPosition(Object object) {
                // return super.getItemPosition(object);
                return POSITION_NONE;
            }
        };
        viewPager.setAdapter(pagerAdapter);
    }

    /**
     * 设置recyclerview的adapter
     *
     * @param recyclerView
     * @param list
     */
    private void setRecyclerAdapter(RecyclerView recyclerView, final List<AppModel> list, int viewType) {

        switch (viewType) {
            case APPVIEWTYPE:
            case UPDATEVIEWTYPE:
                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                adapter = new CommonAdapter<AppModel>(getContext(), R.layout.item_app, list) {
                    @Override
                    protected void convert(ViewHolder holder, AppModel t, int position) {
                        final AppModel app = list.get(position);
                        // holder.setImageDrawable(R.id.iv_item_app_icon,
                        // app.getLocalIcon());
                        ImageView iv = holder.getView(R.id.iv_item_app_icon);
                        Glide.with(getActivity()).load(app.getIconUrl()).into(iv);
                        holder.setText(R.id.tv_item_app_name, app.getAppName());
                        holder.setRating(R.id.ratingbar_item_app_score, app.getScore());
                        holder.setText(R.id.tv_item_app_total_size, Util.byte2Mega(app.getSize()));
                        holder.setText(R.id.tv_item_app_version_name, app.getRemoteVersionName());

                        final DownloadInfo downloadInfo = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());

                        if (downloadInfo != null && downloadInfo.getState() == DownloadManager.FINISH) {
                            if (ApkUtils.isInstalled(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
                                holder.setText(R.id.btn_item_app_install, "打开");
                            } else if (ApkUtils.isAvailable(getActivity(), app.getAppPackName())) {
                                holder.setText(R.id.btn_item_app_install, "更新");
                            } else {
                                if (FileUtils.isExist(downloadInfo.getTargetPath())) {
                                    holder.setText(R.id.btn_item_app_install, "安装");
                                } else {
                                    holder.setText(R.id.btn_item_app_install, "下载");
                                }
                            }
                        } else {
                            holder.setText(R.id.btn_item_app_install, "下载");
                        }


                        final View button = holder.getView(R.id.btn_item_app_install);

                        holder.setOnClickListener(R.id.btn_item_app_install, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Message message = new Message();
                                message.what = 999;
                                message.obj = v;
                                handler.sendMessage(message);
                            }
                        });

//                        holder.setOnClickListener(R.id.btn_item_app_install, new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                DownloadInfo info = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());
//                                // 如果该任务的状态为完成
//                                if (info != null && info.getState() == DownloadManager.FINISH) {
//                                    // 如果已经安装则打开; 未安装,判断安装包是否存在. 如果存在则安装, 不存在则重新下载;
//                                    // if (ApkUtils.isAvailable(getContext(),
//                                    // app.getAppPackName())) {
//                                    if (ApkUtils.isInstalled(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
//                                        if (!app.getAppPackName().equals(Util.getPackageName(getActivity()))) {
//                                            ApkUtils.openAPP(getActivity(), app.getAppPackName());
//                                        }
//                                    } else {
//                                        if (FileUtils.isExist(info.getTargetPath())) {
//                                            // TODO 安装
//                                            ApkUtils.installSilent(getActivity(), new File(info.getTargetPath()));
//                                            // ApkUtils.install(getActivity(), new
//                                            // File(info.getTargetPath()));
//                                        } else {
//                                            APPDownloadManager.removeTask(info.getTaskKey());
//                                            APPDownloadManager.addTask(getActivity(), app, info.getListener());
//                                            // TODO 点击下载后跳转到下载列表页面吗?
//                                            // startActivity(AppDownManagerActivity.class);
//                                            SnackbarUtil.showSnackbar(getActivity(), button);
//                                        }
//                                    }
//                                } else {
//                                    APPDownloadManager.addTask(getActivity(), app, null);
//                                    SnackbarUtil.showSnackbar(getActivity(), button);
//                                }
//                            }
//
//                        });
                /*
                 *
				 * refresh(info, app, holder);
				 */
                    }
                };

                adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {

                    @Override
                    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                        intent = new Intent(getActivity(), AppDetailActivity.class);
                        AppModel app = list.get(position);
                        intent.putExtra(Constant.DATA, app);
                        startActivity(intent);
                    }
                });
                recyclerView.setAdapter(adapter);
                break;
            case MANAGERVIEWTYPE:
                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                CommonAdapter<AppManagerModel> adapter = new CommonAdapter<AppManagerModel>(getContext(), R.layout.item_rv_manager_apps, appManagerModelList) {
                    @Override
                    protected void convert(ViewHolder holder, AppManagerModel appModel, int position) {
                        appModel = appManagerModelList.get(position);
                        holder.setText(R.id.tv_rv_manager_apps_title, appModel.getAppManagerTitle());
                        holder.setText(R.id.tv_rv_manager_apps_content, appModel.getAppManagerContent());
                    }
                };

                adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {

                    @Override
                    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                        Intent startManager = null;
                        switch (position) {
                            case 0:
                                startManager = new Intent(getActivity(), DownloadManagerActivity.class);
                                break;
                            case 1:
                                startManager = new Intent(getActivity(), DownloadManagerActivity.class);
                                break;
                            case 2:
                                startManager = new Intent(getActivity(), DownloadManagerActivity.class);
                                break;
                        }
                        startActivity(startManager);
                    }
                });
                recyclerView.setAdapter(adapter);
                break;
        }
    }

    /**
     * 更新 暂无用
     *
     * @param info
     * @param app
     * @param holder
     */
    // protected void refresh(final DownloadInfo info, final AppModel app, final
    // ViewHolder holder) {
    //
    // DownloadListener listener = new MyDownloadListener();
    // listener.setUserTag(holder);
    //
    // if (info != null) {
    // info.setListener(listener);
    // }
    //
    // switch (info.getState()) {
    // case DownloadManager.NONE:
    // holder.setText(R.id.btn_item_app_install, "安装");
    // break;
    // case DownloadManager.WAITING:
    // holder.setText(R.id.btn_item_app_install, "准备");
    // break;
    // case DownloadManager.DOWNLOADING:
    // holder.setText(R.id.btn_item_app_install, "准备");
    // break;
    // case DownloadManager.PAUSE:
    // holder.setText(R.id.btn_item_app_install, "暂停");
    // break;
    // case DownloadManager.FINISH:
    // holder.setText(R.id.btn_item_app_install, "安装");
    // ApkUtils.isAvailable(getContext(), app.getAppPackName());
    // break;
    // case DownloadManager.ERROR:
    //
    // break;
    //
    // default:
    // break;
    // }
    //
    // holder.setOnClickListener(R.id.btn_item_app_install, new
    // OnClickListener() {
    // @Override
    // public void onClick(View v) {
    // if (info != null && info.getState() == DownloadManager.FINISH) {
    // ApkUtils.install(getContext(), new File(info.getTargetPath()));
    // }else {
    // GetRequest request = new GetRequest(Util.getDownloadUrl(info.getUrl()));
    // DownloadListener listener = new MyDownloadListener();
    // listener.setUserTag(holder);
    // DownloadService.getDownloadManager().addTask(app.getAppName(),
    // app.getUrl(), request, listener);
    // startActivity(AppDownManagerActivity.class);
    // }
    // }
    // });
    // }

    /**
     *
     * @author cxy
     *
     */
    // class MyDownloadListener extends DownloadListener{
    //
    // @Override
    // public void onProgress(DownloadInfo downloadInfo) {
    // if (getUserTag() == null) {
    // return;
    // }
    // ViewHolder holder = (ViewHolder) getUserTag();
    // AppModel app = (AppModel)
    // AppCacheUtils.getInstance(getContext()).getObject(downloadInfo.getTaskKey());
    // refresh(downloadInfo, app, holder);
    // }
    //
    // @Override
    // public void onFinish(DownloadInfo downloadInfo) {
    // }
    //
    // @Override
    // public void onError(DownloadInfo downloadInfo, String errorMsg, Exception
    // e) {
    // }
    //
    // }

    /**
     * 是否显示refresh
     *
     * @param b
     */
    private void showRefresh(final boolean b) {
        swipe_refresh.post(new Runnable() {
            @Override
            public void run() {
                swipe_refresh.setRefreshing(b);
            }
        });
    }


}

